package com.charlie.mail;

import java.util.Date;
import java.util.LinkedHashSet;
import java.util.Set;
import javax.annotation.Resource;
import javax.ejb.Singleton;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 *
 * @author Vitaliy Mostipaka <imprtat@gmail.com>
 */
@Singleton
public class Mail implements MailLocal {

    @Resource(lookup = "CharlieMail")
    private Session session;
    
    private InternetAddress[] parseMails(String to) {
        String[] to_list = to.split("[;, ]");
        Set<InternetAddress> address_list = new LinkedHashSet<InternetAddress>(to_list.length);
        for (int i=0; i<to_list.length; i++) {
            try {
                InternetAddress address = new InternetAddress(to_list[i].trim());
                address.validate();
                address_list.add(address);
            } catch (AddressException ex) {}
        }
        return address_list.toArray(new InternetAddress[0]);
    }

    @Override
    public void send(String to, String subject, String body) {
        MimeMessage message = new MimeMessage(session);
        try {
            InternetAddress from = new InternetAddress(session.getProperty("mail.from"));
            message.setFrom(from);
            message.setRecipients(Message.RecipientType.TO, parseMails(to));
            message.setSubject(subject);
            message.setSentDate(new Date());
            message.setText(body);
            Transport.send(message);
        } catch (MessagingException ex) {
        }
    }
    
    @Override
    public void send(String to, String subject, MailTemplate tpl) {
        send(to, subject, tpl.getData());
    }

}
